package com.my.spring.dispatcher;

import java.io.PrintWriter;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.my.spring.constant.SpringIocConstant;
import com.my.spring.ioc.AbstractIoc;
import com.my.spring.ioc.ConstrollerMappingIoc;
import com.my.spring.ioc.RequestMappingIoc;

public class DispatcherServlet extends FrameWorkServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public void service(HttpServletRequest req, HttpServletResponse resp) {
		try {
			String url = req.getPathInfo().substring(1);
			//获取所有的缓存中所有的请求路径对应的处理类
			AbstractIoc mapping = (RequestMappingIoc) req.getServletContext()
					.getAttribute(SpringIocConstant.REQUESTMAPPING);

			if (mapping.getValue(url) != null) {
				//得到具体对处理类
				AbstractIoc conMapping = (ConstrollerMappingIoc) req.getServletContext()
						.getAttribute(SpringIocConstant.CONSTROLLERMAPPING);
				Object[] args= {};
				//如果reqest中有参数
				if(req.getParameterMap().size()>0)
				{
					args=new Object[1];
					args[0]=req;
				}
				Method m = (Method) mapping.getValue(url);
				Object obj = conMapping.getValue(m);
				m.setAccessible(true);
				//请求处理类型
				Object object=m.invoke(obj,args);
				String json=JSONArray.toJSONString(object);
				resp.setCharacterEncoding("UTF-8");
				PrintWriter out = resp.getWriter();
				out.println(json);
				out.flush();
				out.close();
				
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
